package cn.tj.wenda.cloud.interceptor;

import cn.tj.wenda.cloud.entity.ResponseBean;
import cn.tj.wenda.cloud.security.JsonWebToken;
import cn.tj.wenda.cloud.util.ConstUtil;
import cn.tj.wenda.cloud.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 * @author Wenda
 */
@Component
@Slf4j
public class UrlInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (request.getHeader(ConstUtil.TOKEN) == null) {
            this.returnErrorJson(request, response, "请提供" + ConstUtil.TOKEN);
            return false;
        }

        if (StringUtils.isEmpty(request.getHeader(ConstUtil.TOKEN))) {
            this.returnErrorJson(request, response, "请提供" + ConstUtil.TOKEN);
            return false;
        }

        String token = request.getHeader(ConstUtil.TOKEN);
        int ret = JsonWebToken.checkJWT(token);
        if (ret == 0) {
            return true;
        } else {
            String errMsg = JsonWebToken.getCheckMsg(ret);
            this.returnErrorJson(request, response, errMsg);
        }

        return false;
    }

    private void returnErrorJson(HttpServletRequest request, HttpServletResponse response, String errMsg) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(403);
        try {
            writer = response.getWriter();
            ResponseBean res = new ResponseBean();
            res.setErr("403");
            res.setErrMsg(errMsg);
            String resString = JsonUtils.objectToJsonStr(res);
            writer.print(resString);
            log.warn("拦截器成功拦截：" + errMsg + ",URL:" + request.getRequestURI().toString());

        } catch (IOException e) {
            log.error("拦截器输出流异常" + e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
